import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, LoginForm, RegisterForm, AuthState } from '@/types/index'
import { AuthService } from '@/services/auth'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const currentUser = ref<User | null>(null)
  const isAuthenticated = ref(false)
  const loading = ref(false)

  // 计算属性
  const userRole = computed(() => currentUser.value?.role || null)
  const userName = computed(() => currentUser.value?.name || '')
  const userEmail = computed(() => currentUser.value?.email || '')

  // 初始化认证状态
  const initAuth = () => {
    const user = AuthService.getCurrentUser()
    if (user) {
      currentUser.value = user
      isAuthenticated.value = true
    }
  }

  // 开发阶段：临时设置用户角色（用于绕过认证）
  const setDevelopmentUser = (role: 'teacher' | 'student') => {
    const mockUser: User = {
      id: `dev-${role}-001`,
      name: role === 'teacher' ? '开发测试老师' : '开发测试学生',
      email: `dev-${role}@example.com`,
      role: role,
      avatar: '',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    currentUser.value = mockUser
    isAuthenticated.value = true
    console.log(`开发模式：已设置为${role === 'teacher' ? '教师' : '学生'}角色`)
  }

  // 用户注册
  const register = async (registerForm: RegisterForm): Promise<{ success: boolean; message: string }> => {
    loading.value = true
    try {
      const result = AuthService.register(registerForm)
      // 注册成功后不自动登录，需要用户手动登录
      return { success: result.success, message: result.message }
    } catch (error) {
      console.error('注册失败:', error)
      return { success: false, message: '注册失败，请重试' }
    } finally {
      loading.value = false
    }
  }

  // 用户登录
  const login = async (loginForm: LoginForm): Promise<{ success: boolean; message: string }> => {
    loading.value = true
    try {
      const result = AuthService.login(loginForm)
      if (result.success && result.user) {
        currentUser.value = result.user
        isAuthenticated.value = true
      }
      return { success: result.success, message: result.message }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: '登录失败，请重试' }
    } finally {
      loading.value = false
    }
  }

  // 用户登出
  const logout = () => {
    try {
      AuthService.logout()
      currentUser.value = null
      isAuthenticated.value = false
    } catch (error) {
      console.error('登出失败:', error)
    }
  }

  // 检查用户权限
  const hasRole = (role: 'teacher' | 'student'): boolean => {
    return currentUser.value?.role === role
  }

  // 检查是否为教师
  const isTeacher = computed(() => hasRole('teacher'))

  // 检查是否为学生
  const isStudent = computed(() => hasRole('student'))

  // 更新用户信息
  const updateUser = (userData: Partial<User>) => {
    if (currentUser.value) {
      currentUser.value = { ...currentUser.value, ...userData }
      AuthService.setCurrentUser(currentUser.value)
    }
  }

  return {
    // 状态
    currentUser,
    isAuthenticated,
    loading,
    
    // 计算属性
    userRole,
    userName,
    userEmail,
    isTeacher,
    isStudent,
    
    // 方法
    initAuth,
    setDevelopmentUser, // 开发阶段临时方法
    register,
    login,
    logout,
    hasRole,
    updateUser
  }
})